package com.pms.api;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.base.Joiner;
import com.pms.controller.BaseController;
import com.pms.entity.*;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.rpc.UserService;
import com.pms.service.IGroupIotAgencyService;
import com.pms.service.IIotAgencyService;
import com.pms.service.IIotEqCameraService;
import com.pms.service.IIotWaterPumpGroupService;
import com.pms.util.FluoriteCloudUtile;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hm on 2018/9/20.
 */
@RestController
@RequestMapping(value = "/pms/apiEqCamera")
@Api(value="App二汞摄像头接口",description = "App二汞摄像头接口")
public class ApiIotEqCameraController extends BaseController {

    @Autowired
    IIotEqCameraService iotEqCameraService;
    @Autowired
    private com.pms.cache.utils.RedisCacheUtil RedisCacheUtil;
    @Autowired
    UserService userService;
    @Autowired
    IGroupIotAgencyService groupIotAgencyService;
    @Autowired
    IIotAgencyService iotAgencyService;
    @Autowired
    IIotAgencyService orgService;
    @Autowired
    IIotWaterPumpGroupService waterPumpGroupService;
    /**
     * 根据水泵房查询摄像头
     * @param agencyId
     * @return
     */
    @GetMapping("/selectByEqCameraList")
    @ApiOperation(value = "根据水泵房查询摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agencyId", value = "水泵房ID", required = true, dataType = "Long", paramType = "form"),
    })
    public R selectByEqCameraList(Long agencyId){
        parameterIsNull(agencyId,"水泵房ID不能为空");
        List<IotEqCamera> list= iotEqCameraService.selectByList(agencyId);
        if (null!=list||list.size()>0){
            for (int x=0;x< list.size();x++){
                capture(Long.parseLong(list.get(x).getEqId().toString()));
            }
        }
        return  R.ok().put("data",list);
    }



    public R capture(Long eqId){
        IotEqCamera eqCamera=iotEqCameraService.selectById(eqId);
        parameterIsNull(eqCamera," 该摄像头信息不存在");
        String  redisPhoto =RedisCacheUtil.getVlueStr("PMS_PhotoCapture"+eqId);
        if (redisPhoto == null){
            //如果缓存对象过时
            JSONObject capture = FluoriteCloudUtile.capture(eqCamera.getKey(),"1",eqCamera.getToken());
            if(capture.getString("code").equals("200")){
                JSONObject data= capture.getJSONObject("data");
                Object img=data.get("picUrl");
                eqCamera.setPicurl(img.toString());
                iotEqCameraService.updateById(eqCamera);
                RedisCacheUtil.saveAndUpdate("PMS_PhotoCapture"+eqId, img,10);
                return  R.ok().put("data",img);
            }else{
                throw new RRException(capture.toJSONString(),400);
            }
        }else{
            return  R.ok().put("data",redisPhoto);
        }
    }

    /**
     * 根据当前登录用户查询摄像头
     * @param userId
     * @param limit
     * @param page
     * @param name
     * @return
     */
    @PostMapping("/selectByEqCameraAndCompanyCodeAll")
    @ApiOperation(value = "根据当前登录用户查询摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "当前用户ID", required = true, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name="limit",value="分页条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="page",value="分页页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="name",value="查询条件",required = false,dataType = "String",paramType="form"),
     })
    public R selectByEqCameraAndCompanyCodeAll(Long userId,int limit,int page,String name){
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        parameterIsNull(userId,"请填写用户ID");
        Map<String,Object> map=new HashMap<>();
        Page<IotEqCamera> pageList = new Page<>(page,limit);
        UserInfo user= userService.selectbyPipUser(userId);
        if (null==user||null==user.getId()){return  R.error(400,"用户信息不存在");}
        //管理员
        if (user.getGroupType()==1){
            map.put("companyCode",user.getCompanyCode());
            map.put("type",1);
        }else {
            List<String> str=new ArrayList<>();
            List<GroupIotAgency> list=groupIotAgencyService.selectList(
                    new EntityWrapper<GroupIotAgency>().eq("group_id",user.getGroupId()));
            if (list.size()>0){
                for (int x=0;x<list.size();x++){
                    str.add(list.get(x).getAgencyId().toString());
                }
               String ids= Joiner.on(",").join(str);
                map.put("ids",ids);
                //获取到当前用户所绑定的所有水泵房
                List<Long> agencyId= iotAgencyService.selectByAgencyIdS(map);
                String idList= Joiner.on(",").join(agencyId);
                map.put("idList",idList);
            }
            map.put("type",2);
        }
        if (StringUtils.isNotBlank(name)){
            map.put("name","and (belonged_house like '%"+name+"%' or belonged_community like  '%"+name+"%')");
        }
        map.put("limit",limit);
        map.put("page",(page-1) * limit);
        pageList = iotEqCameraService.selectByEqCameraAndCompanyCodeAll(pageList,map);
        return R.ok().put("data",pageList);
    }


    /**
     * 根据水泵房或者小区查询摄像头
     * @param agencyId
     * @param communityId
     * @param type
     * @return
     */
    @PostMapping("/getByEqCamera")
    @ApiOperation(value = "根据水泵房或者小区查询摄像头")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "agencyId", value = "水泵房ID", required = false, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "communityId", value = "小区ID", required = true, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "type", value = "请求方式(3小区4水泵房)", required = true, dataType = "int", paramType = "form"),
            @ApiImplicitParam(name="limit",value="分页条数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="page",value="分页页数",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="name",value="查询条件",required = false,dataType = "String",paramType="form"),
    })
    public R getByEqCamera(Long agencyId,Long communityId,int type,int  limit, int page,String name){
        parameterIsNull(communityId,"请选择一个小区");
        if (limit<1){limit=10;}
        if (page<1){page=1;}
        Map<String,Object> map=new HashMap<>();
        Page<IotEqCamera> pageList = new Page<>(page,limit);
        if (type==3){
            IotAgency  agency=iotAgencyService.selectById(communityId);
            if (agency==null&& agency.getLevel()!=3){return  R.error(400,"小区信息不存在！");}
            List<IotAgency> list=iotAgencyService.selectList(new EntityWrapper<IotAgency>().eq("parent_id",agency.getId()));
            if (list.size()>0){
                List<Long> str=new ArrayList<>();
                for (int x=0;x<list.size();x++){
                    str.add(list.get(x).getId());
                };
                String idList= Joiner.on(",").join(str);
                map.put("idList",idList);
            }
        }else if (type==4){
            parameterIsNull(agencyId,"请选择一个水泵房！");
            map.put("idList",agencyId);
        }
        if (StringUtils.isNotBlank(name)){
            map.put("name","and (belonged_house like '%"+name+"%' or belonged_community like  '%"+name+"%')");
        }
        map.put("type",2);
        map.put("limit",limit);
        map.put("page",(page-1) * limit);
        pageList = iotEqCameraService.selectByEqCameraAndCompanyCodeAll(pageList,map);
        return R.ok().put("data",pageList);
    }

        /*
          * 查询分区树结构
          * @param
          * @return
          */
    @ApiOperation(value = "查询机构树结构 通过登录用户")
    @RequestMapping(value = "/readAgencyTreeByUser",method = RequestMethod.POST)
    @ApiImplicitParams({
            @ApiImplicitParam(name="readTreeLevel",value="查询树结构层级(1-系统,2-物业/公司,3-小区,4-水泵房,5-水泵组)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="checked",value="是否默认全部选中(0-未选中(默认),1-选中)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="opened",value="是否默认全部展开(0-未展开(默认),1-展开)",required = false,dataType = "int",paramType="form"),
    })
    public R readAgencyTreeByUser(Integer readTreeLevel,Integer checked,Integer opened){
        if(readTreeLevel==null||readTreeLevel<1){readTreeLevel = 5;}// 默认查询5级
        if(opened==null||opened!=1){opened=0;}
        if(checked==null||checked!=1){checked=0;}
        Map<String,Object> returnMap = new HashMap<String,Object>();
        returnMap.put("id",-1L);
        returnMap.put("name","系统");
        returnMap.put("code","system");
        returnMap.put("parentId",-2);
        returnMap.put("level",1);
        returnMap.put("checked",checked);
        returnMap.put("opened",opened);
        if(readTreeLevel==1){
            returnMap.put("children",new ArrayList< Map<String,Object>>());
            return R.ok().put("data",returnMap);
        }
        // 获取当前角色 拥有的 机构id权限
        String agencyIdsStr = null;
        Integer roleType =null;
        Long roleId =null;
        String companyCode =null;
        try {
            roleType = getCurrentRoleType();
            roleId = getCurrentRoleId();
            companyCode = getCurrentCompanyCode();
        }catch (NumberFormatException ex){
            return  R.error(400,"请重新登录");
        }
        if(roleId==null||roleType==null||companyCode==null){
            return  R.error(400,"请重新登录");
        }
        if(roleType!=1) {
            agencyIdsStr = groupIotAgencyService.getAgencyIdsStrByGroupId( roleId+ "");
            Assert.parameterIsBlank(agencyIdsStr,"您暂无机构权限，请联系管理员");
        }
        Wrapper<IotAgency> agencyWp = new EntityWrapper<IotAgency>();
        agencyWp.eq("company_code",companyCode);
        if(agencyIdsStr!=null){
            agencyWp.in("agency_id",agencyIdsStr);
        }
        if(readTreeLevel<4){
            agencyWp.le("agency_level",readTreeLevel);//  判断 机构等级  <=
        }
        List<Map<String,Object>> treeList = orgService.selectMapList(agencyWp);
        if(readTreeLevel>4){//查询到水泵组
            Wrapper<IotWaterPumpGroup> waterPumpGroupWp = new EntityWrapper<IotWaterPumpGroup>();
            waterPumpGroupWp.eq("company_code",companyCode);
            if(agencyIdsStr!=null){
                waterPumpGroupWp.in("house_id",agencyIdsStr);
            }
            treeList.addAll( waterPumpGroupService.selectMapList(waterPumpGroupWp) );
        }
        List<Map<String,Object>> treeChildrenList = orgService.agencyFactorTree(treeList,checked,opened);
        returnMap.put("children",treeChildrenList);
        return R.ok().put("data",returnMap);
    }
}
